package com.nf.controller.home;

import com.google.gson.Gson;
import com.nf.controller.BaseServlet;
import com.nf.dao.OrderInfoDao;
import com.nf.dao.TicketInfoDao;
import com.nf.dao.impl.OrderInfoDaoImpl;
import com.nf.dao.impl.TicketInfoDaoImpl;
import com.nf.entity.OrderInfo;
import com.nf.entity.TicketInfo;
import com.nf.util.GsonUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 编写servlet，实现根据订单ID 修改订单的支付状态，并添加相应的影票记录
 */
@WebServlet("/api/UpdateOrderStatusByIdServlet.do")
public class UpdateOrderStatusByIdServlet extends BaseServlet {
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader reader= req.getReader();
        String str=null;
        String jsonParams="";
        while ((str=reader.readLine())!=null){
            jsonParams=jsonParams+str;
        }
        Map<String,String> map= GsonUtil.parseMap(jsonParams);
        int id= Integer.parseInt(map.get("orderId"));

        OrderInfoDao dao=new OrderInfoDaoImpl();
        int r= dao.updateStatus(id);

        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();

        if(r==1){
            // 修改订单状态成功后，添加影票
            OrderInfo order= dao.selectById(id);
            String seats= order.getSeats();

            String[] arr=seats.split(" ");
            float price=order.getPrice()/ (arr.length-1);

            TicketInfoDao dao2=new TicketInfoDaoImpl();
            int m=0;
            for(int i=1;i< arr.length;i++){
                String seat= arr[i];

                TicketInfo ticket=new TicketInfo();
                ticket.setFilmName(order.getFilmName());
                ticket.setHallName(order.getHallName());
                ticket.setShowDate(order.getShowDate());
                ticket.setStartTime(order.getStartTime());
                ticket.setPrice(price);
                ticket.setTicketSeat(seat);
                ticket.setFilmId(order.getFilmId());
                ticket.setShowId(order.getShowId());

                dao2.add(ticket);
                m++;
            }
            if(m== arr.length-1){
                out.print(new Gson().toJson(successJson("支付成功")));
            }
        }else {
            out.print(new Gson().toJson(errorJson("支付失败")));
        }
        out.flush();
        out.close();
    }
}
